const pageHelper = require('../../../../../helper/page_helper.js');
const cloudHelper = require('../../../../../helper/cloud_helper.js');
const projectSetting = require('../../../public/project_setting.js');
import TaskStore from '../../../../../store/modules/task_store';
import { createStoreBindings } from 'mobx-miniprogram-bindings';
import Day from 'dayjs';

Page({
  /**
   * 页面的初始数据
   */
  data: {
    isLoad: false,
    isLoading: true,
    taskId: '',
    task: null,
    
    // 标签页
    tabCur: 0,
    tabs: ['详情', '子任务', '评论', '历史'],
    
    // 操作菜单状态
    showActionMenu: false,
    showStatusMenu: false,
    showDeleteConfirm: false,
    
    // 评论相关
    commentText: '',
    
    // 子任务相关
    newSubtaskTitle: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    // 创建Store绑定
    this.storeBindings = createStoreBindings(this, {
      store: TaskStore,
      fields: [
        'task',
        'subTasks',
        'comments',
        'taskHistory',
        'isTaskLoading'
      ],
      actions: [
        'getTaskDetail',
        'refreshTaskDetail',
        'updateTaskStatus',
        'deleteTask',
        'addTaskComment',
        'addSubtask'
      ]
    });

    this.options = options;
    
    if (!options.id || options.id.length < 1) {
      pageHelper.showNoneToast('参数错误');
      this.setData({
        isLoad: true,
        isLoading: false
      });
      return;
    }
    
    this.loadDetail();
  },
  
  async loadDetail() {
    try {
      this.setData({ isLoading: true });
      
      await this.getTaskDetail(this.options.id);
      
      this.setData({
        isLoad: true,
        isLoading: false
      });
    } catch (err) {
      console.error('[任务详情] 加载失败:', err);
      pageHelper.showErrToast('加载失败，请重试');
      this.setData({
        isLoad: true,
        isLoading: false
      });
    }
  },
  
  /**
   * 切换标签页
   */
  switchTab(e) {
    const tabIdx = e.currentTarget.dataset.idx;
    this.setData({
      tabCur: tabIdx
    });
  },
  
  /**
   * 显示操作菜单
   */
  showActionMenu() {
    this.setData({
      showActionMenu: true
    });
  },
  
  /**
   * 隐藏操作菜单
   */
  hideActionMenu() {
    this.setData({
      showActionMenu: false
    });
  },
  
  /**
   * 显示状态菜单
   */
  showStatusMenu() {
    this.setData({
      showStatusMenu: true
    });
  },
  
  /**
   * 隐藏状态菜单
   */
  hideStatusMenu() {
    this.setData({
      showStatusMenu: false
    });
  },
  
  /**
   * 显示删除确认对话框
   */
  showDeleteConfirm() {
    this.setData({
      showDeleteConfirm: true,
      showActionMenu: false
    });
  },
  
  /**
   * 关闭删除确认对话框
   */
  hideDeleteConfirm() {
    this.setData({
      showDeleteConfirm: false
    });
  },
  
  /**
   * 跳转到编辑页
   */
  gotoEdit() {
    const id = this.options.id;
    wx.navigateTo({
      url: '../edit/task_edit?id=' + id,
     timeout: 10000, fail: function(err) {
        // 处理超时错误
        if (err.errMsg && err.errMsg.includes("timeout")) {
          wx.showToast({
            title: "页面加载超时，请重试",
            icon: "none"
          });
          return;
        }
        
        // 处理其他错误
        console.error("页面跳转失败:", err);
        wx.showToast({
          title: "页面跳转失败",
          icon: "none"
        });
      }});
    this.hideActionMenu();
  },
  
  /**
   * 更新任务状态
   */
  async updateStatus(e) {
    try {
      const status = e.currentTarget.dataset.status;
      
      // 检查状态是否发生变化
      if (this.data.task && this.data.task.status === status) {
        this.setData({
          showStatusMenu: false
        });
        return;
      }
      
      const userId = pageHelper.getUserId();
      
      await this.updateTaskStatus(this.options.id, status, userId);
      
      this.setData({
        showStatusMenu: false
      });
      
      pageHelper.showSuccToast('状态已更新');
    } catch (err) {
      console.error('[任务详情] 更新状态失败:', err);
      pageHelper.showErrToast('更新状态失败，请重试');
    }
  },
  
  /**
   * 提交评论
   */
  async submitComment() {
    try {
      const content = this.data.commentText;
      if (!content || content.length < 1) {
        pageHelper.showErrToast('请输入评论内容');
        return;
      }
      
      const userInfo = pageHelper.getUserInfo();
      const userId = userInfo._id || pageHelper.getUserId();
      const userName = userInfo.NAME || '用户';
      
      await this.addTaskComment(this.options.id, content, userId, userName);
      
      this.setData({
        commentText: ''
      });
      
      pageHelper.showSuccToast('评论已提交');
    } catch (err) {
      console.error('[任务详情] 提交评论失败:', err);
      pageHelper.showErrToast('提交失败，请重试');
    }
  },
  
  /**
   * 输入评论
   */
  onCommentInput(e) {
    this.setData({
      commentText: e.detail.value
    });
  },
  
  /**
   * 输入子任务标题
   */
  onSubtaskInput(e) {
    this.setData({
      newSubtaskTitle: e.detail.value
    });
  },
  
  /**
   * 添加子任务
   */
  async addSubtaskHandler() {
    try {
      const title = this.data.newSubtaskTitle;
      if (!title || title.length < 1) {
        pageHelper.showErrToast('请输入子任务标题');
        return;
      }
      
      const subtaskData = {
        title: title,
        status: 'pending'
      };
      
      await this.addSubtask(this.options.id, subtaskData);
      
      this.setData({
        newSubtaskTitle: ''
      });
      
      pageHelper.showSuccToast('子任务已添加');
    } catch (err) {
      console.error('[任务详情] 添加子任务失败:', err);
      pageHelper.showErrToast('添加子任务失败，请重试');
    }
  },
  
  /**
   * 切换子任务状态
   */
  async toggleSubtask(e) {
    try {
      const id = e.currentTarget.dataset.id;
      if (!id) return;
      
      const subtask = this.data.subTasks.find(item => item._id === id);
      if (!subtask) return;
      
      const newStatus = subtask.status === 'completed' ? 'pending' : 'completed';
      
      await cloudHelper.callCloudSumbit('task/update_subtask', {
        taskId: this.options.id,
        subtaskId: id,
        status: newStatus
      });
      
      // 刷新任务详情
      await this.refreshTaskDetail(this.options.id);
      
      pageHelper.showSuccToast('状态已更新');
    } catch (err) {
      console.error('[任务详情] 更新子任务状态失败:', err);
      pageHelper.showErrToast('操作失败，请重试');
    }
  },
  
  /**
   * 删除任务
   */
  async confirmDelete() {
    try {
      if (!this.data.task) {
        this.hideDeleteConfirm();
        return;
      }
      
      const projectId = this.data.task.projectId;
      
      await this.deleteTask(this.options.id, projectId);
      
      this.hideDeleteConfirm();
      
      pageHelper.showSuccToast('删除成功');
      
      setTimeout(() => {
        wx.navigateBack({
          delta: 1
        });
      }, 1500);
    } catch (err) {
      console.error('[任务详情] 删除失败:', err);
      pageHelper.showErrToast('删除失败，请重试');
    }
  },

  /**
   * 格式化日期
   */
  formatDate(timestamp) {
    if (!timestamp) return '';
    return Day(timestamp).format('YYYY-MM-DD HH:mm');
  },
  
  /**
   * 计算截止日期状态
   */
  getDueDateStatus(dueDate) {
    if (!dueDate) return '';
    
    const today = Day();
    const due = Day(dueDate);
    
    if (due.isBefore(today, 'day')) {
      return 'overdue';
    } else if (due.isSame(today, 'day')) {
      return 'today';
    } else if (due.diff(today, 'day') <= 2) {
      return 'upcoming';
    }
    
    return '';
  },
  
  /**
   * 获取优先级文本
   */
  getPriorityText(priority) {
    const priorityMap = {
      'low': '低',
      'normal': '中',
      'high': '高',
      'urgent': '紧急'
    };
    
    return priorityMap[priority] || '中';
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // 解绑Store
    this.storeBindings.destroyStoreBindings();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  async onPullDownRefresh() {
    await this.refreshTaskDetail(this.options.id);
    wx.stopPullDownRefresh();
  }
}); 